import { Component } from "react";
import { Card, Form, Input, Button, Checkbox, message } from "antd";
import styles from "./index.module.scss";
import logo from "assets/logo.png";

//引入API
import { LoginAPI } from "api/user";

export default class Login extends Component {
  render() {
    return (
      <div className={styles.login}>
        <Card
          className="login-container"
          style={{ borderRadius: "20px", backgroundColor: "#ffffffeb" }}
        >
          <img className="login-logo" src={logo} alt="" />
          {/* 表单 */}
          <Form size="large" onFinish={this.onFinish}>
            <Form.Item
              name="mobile"
              initialValue="13811111111"
              rules={[
                { required: true, message: "请输入手机号" },
                { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
              ]}
              validateTrigger="onBlur"
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item
              name="code"
              initialValue="246810"
              rules={[
                { required: true, message: "请输入验证码" },
                { pattern: /^\d{6}$/, message: "请输入验证码错误" },
              ]}
              validateTrigger="onBlur"
            >
              <Input placeholder="请输入验证码" />
            </Form.Item>

            <Form.Item
              name="agree"
              valuePropName="checked"
              rules={[
                {
                  validator: (_, value) =>
                    value === true
                      ? Promise.resolve()
                      : Promise.reject("请阅读并同意用户协议"),
                },
              ]}
              validateTrigger={["onFinish", "onChange"]}
            >
              <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" block shape="round">
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  }
  //登录
  onFinish = async (values) => {
    try {
      const res = await LoginAPI({ mobile: values.mobile, code: values.code });
      // 存储token
      localStorage.setItem("geek_pc", res.data.token);
      // 跳转到首页
      this.props.history.push("/");
      message.success("登录成功", 1);
    } catch (err) {
      message.error(err.response.data.message, 1);
    }
  };
}
